iT邦幫忙

2024 iThome 鐵人賽

DAY 19
0
Modern Web

asp.net core 分層架構快速上手系列 第 20

Day19 添加角色與權限控管

  • 分享至 

  • xImage
  •  
  • Utility新增

新增SD.cs,定義四種角色,:

public static class SD
    {
        public const string Role_Customer = "Customer";
        public const string Role_Employee = "Employee";
        public const string Role_Manager = "Manager";
        public const string Role_Admin = "Admin";
    }
  • 新增 EmailSender.cs
    安裝本機板套件:Microsoft.AspNetCore.Identity.UI
public class EmailSender : IEmailSender
    {
        public Task SendEmailAsync(string email, string subject, string htmlMessage)
        {
            return Task.CompletedTask;
        }
    }

https://ithelp.ithome.com.tw/upload/images/20240921/20147438Tio1l4Gfr2.png

  • 添加角色與權限控管
    1.開啟Program.cs,增加角色的讀取;
    2.修改:builder.Services.AddDefaultIdentity
    builder.Services.AddIdentity<IdentityUser, IdentityRole>(options => options.SignIn.RequireConfirmedAccount = true).AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();
    3.設置登入、登出、拒絕訪問的路徑(權限不足時導入頁面),新增:
builder.Services.ConfigureApplicationCookie(options =>
{
    options.LoginPath = $"/Identity/Account/Login";
    options.LogoutPath = $"/Identity/Account/Logout";
    options.AccessDeniedPath = $"/Identity/Account/AccessDenied";
});

4.新增Email注入:

builder.Services.AddScoped<IEmailSender, EmailSender>();

右鍵新增 using Utility;

https://ithelp.ithome.com.tw/upload/images/20240921/2014743829ToJl2W0J.png

  • 添加角色與權限控管

開啟Areas\Identity\Pages\Account\Register.cshtml.cs

private readonly SignInManager<IdentityUser> _signInManager;
private readonly RoleManager<IdentityRole> _roleManager;
private readonly UserManager<IdentityUser> _userManager;
private readonly IUserStore<IdentityUser> _userStore;
private readonly IUserEmailStore<IdentityUser> _emailStore;
private readonly ILogger<RegisterModel> _logger;
private readonly IEmailSender _emailSender;
private readonly IUnitOfWork _unitOfWork;
public RegisterModel(
    UserManager<IdentityUser> userManager,
    RoleManager<IdentityRole> roleManager,
    IUserStore<IdentityUser> userStore,
    SignInManager<IdentityUser> signInManager,
    ILogger<RegisterModel> logger,
    IEmailSender emailSender,
    IUnitOfWork unitOfWork)
{
    _roleManager = roleManager;
    _userManager = userManager;
    _userStore = userStore;
    _emailStore = GetEmailStore();
    _signInManager = signInManager;
    _logger = logger;
    _emailSender = emailSender;
    _unitOfWork = unitOfWork;
}

https://ithelp.ithome.com.tw/upload/images/20240921/20147438TansgtrASI.png

  • 調整註冊頁面

  • 同樣是Register.cshtml.cs找到public class InputModel

  • public string Password { get; set; },下方新增:

public string? Role { get; set; }
[Required]
public string Name { get; set; }
public string? Address { get; set; }
public string? PhoneNumber { get; set; }
[ValidateNever]
public IEnumerable<SelectListItem> RoleList { get; set; }

1.Name、 Address是自定義Model的屬性;PhoneNumber為AspNetUsers本身的屬性。
2.如果出現錯誤,則點選using Microsoft.AspNetCore.Mvc.Rendering;
https://ithelp.ithome.com.tw/upload/images/20240921/20147438FAM00PotkT.png

  • 修改OnGetAsync
    再往下找到OnGetAsync,新增程式碼:SD的部分Using Utility
public async Task OnGetAsync(string returnUrl = null)
{
    if (!_roleManager.RoleExistsAsync(SD.Role_Customer).GetAwaiter().GetResult())
    {
_roleManager.CreateAsync(new IdentityRole(SD.Role_Customer)).GetAwaiter().GetResult();
_roleManager.CreateAsync(new IdentityRole(SD.Role_Manager)).GetAwaiter().GetResult();
_roleManager.CreateAsync(new IdentityRole(SD.Role_Employee)).GetAwaiter().GetResult();
_roleManager.CreateAsync(new IdentityRole(SD.Role_Admin)).GetAwaiter().GetResult();
    }

    Input = new()
    {
RoleList = _roleManager.Roles.Select(x => x.Name).Select(i => new SelectListItem
{
    Text = i,
    Value = i
})
    };
    ReturnUrl = returnUrl;
    ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();

https://ithelp.ithome.com.tw/upload/images/20240921/20147438wtbF9TqcXb.png

  • 修改OnPostAsync

var result = await _userManager.CreateAsync(user, Input.Password);上方新增:

user.Name = Input.Name;
user.Address = Input.Address;
user.PhoneNumber = Input.PhoneNumber;

https://ithelp.ithome.com.tw/upload/images/20240921/2014743874b0VcjdlH.png

  • if (result.Succeeded)內新增:
if (!String.IsNullOrEmpty(Input.Role))
{
await _userManager.AddToRoleAsync(user, Input.Role);
}
else
{
await _userManager.AddToRoleAsync(user, SD.Role_Customer);
}

根據 Input.Role 的值, 加入到指定的角色中。如果 Input.Role 有值,則使用該值;
否則,使用預設 SD.Role_Customer 角色。
https://ithelp.ithome.com.tw/upload/images/20240921/20147438AUXPOdGtRj.png


上一篇
Day18 自定義註冊資料
下一篇
Day20 修改註冊頁面
系列文
asp.net core 分層架構快速上手31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言